package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocke.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServicImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private DishMapper dishMapper;

//用户下单
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        Long userId = BaseContext.getCurrentId();
        //检查地址簿和购物车是否空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.select(shoppingCart);
        if (shoppingCarts == null){
            throw  new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //插入一条订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orderMapper.insert(orders);
        //插入多条订单明细
        for (ShoppingCart shop: shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shop,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.insert(orderDetail);
        }
        //删除购物车
        shoppingCartMapper.deleteByUserId(userId);
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setId(orders.getId());

        return orderSubmitVO;
    }
//用户付款（没有商户信息，不能真正实现付款）
    @Override
    public void pay(OrdersPaymentDTO ordersPaymentDTO) {
        orderMapper.pay(ordersPaymentDTO.getOrderNumber(),1,LocalDateTime.now());
        int id = orderMapper.selectByNumber(ordersPaymentDTO.getOrderNumber());
        //支付后通知管理端
        Map map = new HashMap<>();
        map.put("type",1);//1表示来单
        map.put("orderId",id);
        map.put("content","订单号:"+ordersPaymentDTO.getOrderNumber());
        String s = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(s);
    }
//查询订单信息
    @Override
    public OrderVO orderDetail(Integer id) {
        Orders orders = orderMapper.selectById(id);//查询出订单
        List<OrderDetail> orderDetails = orderDetailMapper.selectById(id);//查询出菜品
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }
//历史订单查询
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageResult pageResult = new PageResult();
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);
        int count = orderMapper.selectCount(ordersPageQueryDTO);
        int start,end;
        start = ordersPageQueryDTO.getPage()-1 * ordersPageQueryDTO.getPageSize() < 0 ? 0 :
                ordersPageQueryDTO.getPage()-1 * ordersPageQueryDTO.getPageSize();
        end = ordersPageQueryDTO.getPage() * ordersPageQueryDTO.getPageSize() <= count ?
                ordersPageQueryDTO.getPage() :
                (count - ordersPageQueryDTO.getPage()-1 * ordersPageQueryDTO.getPageSize() < 0 ? count :
                        count - ordersPageQueryDTO.getPage()-1 * ordersPageQueryDTO.getPageSize());
        List<OrderVO> records = orderMapper.select(ordersPageQueryDTO,start,end);
        for (OrderVO o:records){
            List<OrderDetail> orderDetails = orderDetailMapper.selectById(Math.toIntExact(o.getId()));
            o.setOrderDetailList(orderDetails);
        }
        pageResult.setTotal(count);
        pageResult.setRecords(records);
        return pageResult;
    }
//再来一单
    @Override
    @Transactional
    public void repetition(Integer id) {
        Long userId = BaseContext.getCurrentId();
        shoppingCartMapper.deleteByUserId(userId);//清空购物车
        List<OrderDetail> orderDetails = orderDetailMapper.selectById(id);//查询出菜品
        for (OrderDetail orderDetail: orderDetails){
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
    }
//用户催单
    @Override
    public void reminder(Integer id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null){//没有订单就返回
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap<>();
        map.put("type",2);//1表示催单
        map.put("orderId",id);
        map.put("content","订单号:"+orders.getNumber());
        String s = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(s);
    }
//商家查询订单
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageResult pageResult = new PageResult();
        int count = orderMapper.selectCount(ordersPageQueryDTO);
        int start,end;
        start = ordersPageQueryDTO.getPage()-1 * ordersPageQueryDTO.getPageSize() < 0 ? 0 :
                ordersPageQueryDTO.getPage()-1 * ordersPageQueryDTO.getPageSize();
        end = ordersPageQueryDTO.getPage() * ordersPageQueryDTO.getPageSize() <= count ?
                ordersPageQueryDTO.getPage() :
                (count - ordersPageQueryDTO.getPage()-1 * ordersPageQueryDTO.getPageSize() < 0 ? count :
                        count - ordersPageQueryDTO.getPage()-1 * ordersPageQueryDTO.getPageSize());
        List<OrderVO> records = orderMapper.select(ordersPageQueryDTO,start,end);
        String orderDishs = null;
        for (OrderVO orderVO: records) {
            List<OrderDetail> orderDetails = orderDetailMapper.selectById(Math.toIntExact(orderVO.getId()));
            for (OrderDetail orderDetail: orderDetails) {//把菜品信息拼接起来
                if (orderDishs != null){
                    orderDishs += ","+orderDetail.getName()+orderDetail.getDishFlavor()+orderDetail.getNumber()+"份";
                }else {
                    orderDishs += ","+orderDetail.getName()+orderDetail.getDishFlavor()+orderDetail.getNumber()+"份";
                }
            }
            orderVO.setOrderDishs(orderDishs);
            orderDishs = null;
        }
        pageResult.setRecords(records);
        pageResult.setTotal(count);
        return pageResult;
    }
//各状态订单数
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(3);//已结单待派送
        int confirmed = orderMapper.selectCount(ordersPageQueryDTO);
        ordersPageQueryDTO.setStatus(4);//派送中
        int deliveryInProgress = orderMapper.selectCount(ordersPageQueryDTO);
        ordersPageQueryDTO.setStatus(2);//待接单
        int toBeConfirmed = orderMapper.selectCount(ordersPageQueryDTO);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        return orderStatisticsVO;
    }


}
